package com.core.framework.freemarker.engine;

import java.io.File;
import java.io.IOException;
import java.util.Map;


import com.core.framework.freemarker.FreeMarkerStatics;

import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.FileTemplateLoader;
import freemarker.cache.MruCacheStorage;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.StringTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class TplTemplate implements ITplTemplate ,FreeMarkerStatics{
    private StringTemplateLoader stringLoader = new StringTemplateLoader();
	private Configuration cfg;
	public void init(String tplPath, String cacheTplPath) throws IOException {
		cfg = new Configuration();
		cfg.setEncoding(java.util.Locale.CHINA,ENCODING);
        cfg.setTemplateUpdateDelay(0);
        cfg.setClassicCompatible(true);
        cfg.setNumberFormat("#");
        cfg.setDateFormat("yyyy-MM-dd");
        cfg.setDateTimeFormat("yyyy-MM-dd HH:mm:ss");
        cfg.setLocalizedLookup(false);
        FileTemplateLoader cacheDirLoader = new FileTemplateLoader(new File(cacheTplPath));
        FileTemplateLoader tplPathDirLoader = new FileTemplateLoader(new File(tplPath));
        ClassTemplateLoader classpathDirLoader = new ClassTemplateLoader(this.getClass(), "/");
        cfg.setTemplateLoader(new MultiTemplateLoader(new TemplateLoader[] { stringLoader, tplPathDirLoader, cacheDirLoader, classpathDirLoader }));
        cfg.setCacheStorage(new MruCacheStorage(0, Integer.MAX_VALUE));//模板缓存最大
	}
	public String process(Map<String, Object> rootMap, String templateName) {
		String content = null;
		try {
			
			Template template = cfg.getTemplate(templateName);
			java.io.CharArrayWriter  out=new java.io.CharArrayWriter ();	
			template.process(rootMap,out);		
			content = out.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
		return content;
	}
	public static void main(String[] args )
	{
		
	}

}
